package icu.gking.cart_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import icu.gking.cart_system.mapper.UserMapper;
import icu.gking.cart_system.pojo.User;
import icu.gking.cart_system.service.UserService;
import icu.gking.cart_system.utils.MD5Util;
import icu.gking.cart_system.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    
    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    
    @Autowired
    private UserMapper userMapper;

    @Override
    public Result register(User user) {
        try {
            // 检查用户名是否已存在
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_name", user.getUserName());
            if (userMapper.selectOne(queryWrapper) != null) {
                return Result.error("用户名已存在");
            }

            // 对密码进行MD5加密
            String encryptedPassword = MD5Util.encrypt(user.getPassword());
            user.setPassword(encryptedPassword);

            // 设置默认状态
            user.setStatus(1);

            // 插入用户
            if (userMapper.insert(user) > 0) {
                return Result.success(null);
            }
            return Result.error("注册失败");
        } catch (Exception e) {
            log.error("注册失败", e);
            return Result.error("注册失败：" + e.getMessage());
        }
    }

    @Override
    public Result login(User user) {
        try {
            // 根据用户名查询用户
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_name", user.getUserName())
                    .eq("role", user.getRole());

            User dbUser = userMapper.selectOne(queryWrapper);
            if (dbUser == null) {
                return Result.error("用户名或密码错误");
            }

            // 对输入的密码进行MD5加密
            String encryptedPassword = MD5Util.encrypt(user.getPassword());

            // 比较加密后的密码
            if (!encryptedPassword.equals(dbUser.getPassword())) {
                return Result.error("用户名或密码错误");
            }

            if (dbUser.getStatus() == 0) {
                return Result.error("账号已被禁用");
            }

            return Result.success(dbUser);
        } catch (Exception e) {
            log.error("登录失败", e);
            return Result.error("登录失败：" + e.getMessage());
        }
    }
}




